package com.open.api.wechat.utils;

import com.open.api.wechat.event.common.MsgContent;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;
import java.io.StringReader;
import java.io.StringWriter;

/**
 * @author : zhaoxuan
 * @date : 2021/6/28 20:16
 * @description : XmlUtil
 * @version : 1.0
 */
public class XmlUtil {

    /**
     * @author  zhaoxuan
     * @date  2021/6/28 20:16
     * @params  [xml, clazz]
     * @return  T
     * @description
     */
    public static <T> T xmlToBean(String xml, Class<T> clazz) {

        Object xmlObject = null;
        try {
            JAXBContext context = JAXBContext.newInstance(clazz);
            // 进行将Xml转成对象的核心接口
            Unmarshaller unmarshaller = context.createUnmarshaller();
            StringReader sr = new StringReader(xml);
            xmlObject = unmarshaller.unmarshal(sr);
        } catch (JAXBException e) {
            e.printStackTrace();
        }
        return (T)xmlObject;
    }

    /**
     * @author  zhaoxuan
     * @date  2021/6/28 20:16
     * @params  [bean, clazz]
     * @return  java.lang.String
     * @description
     */
    public static String beanToXml(Object bean,Class<?> clazz){
        String result = "";
        try{
            JAXBContext context = JAXBContext.newInstance(clazz);
            Marshaller marshaller = context.createMarshaller();
            marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
            marshaller.setProperty(Marshaller.JAXB_ENCODING, "UTF-8");
            StringWriter writer = new StringWriter();
            marshaller.marshal(bean,writer);
            result = writer.toString();
        }catch (Exception e){
            e.printStackTrace();
        }
        return result;
    }


    public static void main(String[] args) {
        String xmlBody = "<xml>\n" +
                "  <ToUserName><![CDATA[toUser]]></ToUserName>\n" +
                "  <FromUserName><![CDATA[fromUser]]></FromUserName>\n" +
                "  <CreateTime>1351776360</CreateTime>\n" +
                "  <MsgType><![CDATA[link]]></MsgType>\n" +
                "  <Title><![CDATA[公众平台官网链接]]></Title>\n" +
                "  <Description><![CDATA[公众平台官网链接]]></Description>\n" +
                "  <Url><![CDATA[url]]></Url>\n" +
                "  <MsgId>1234567890123456</MsgId>\n" +
                "</xml>";
        MsgContent msgContent = XmlUtil.xmlToBean(xmlBody, MsgContent.class);
        System.out.println(JsonUtil.toJsonString(msgContent));
    }
}
